<?php
function create_dir( $dir, $chmod='0777'){
	if( mkdir($dir) ){
		@chmod($dir,$chmod);
		return true;
	}else{
		return false;
	}	
}

function create_file( $root, $name, $data=NULL, $chmod='0777' ){
	$path = $root.DIRECTORY_SEPARATOR.$name;
	$f = fopen($path,'w+');
	if(!$f) return false;
	if( $data ) fputs($f, $data );
	@chmod($path,$chmod);
	fclose($f);
	return true;
}

/*
    This is a function that can get max size of file upload
	Base on server and application	
*/
function get_max_size_upload( $app_size = 0 ){
	$max_upload = (int)(ini_get('upload_max_filesize'));
	$max_post = (int)(ini_get('post_max_size'));
	$memory_limit = (int)(ini_get('memory_limit'));
	return min($max_upload, $max_post, $memory_limit, $app_size );
}

function get_file_type( $filename, $name ){
	if (function_exists('finfo_open')) {
		$finfo = finfo_open(FILEINFO_MIME);
		$mimetype = finfo_file($finfo, $filename);
		finfo_close($finfo);
		return $mimetype;
    }else if( function_exists('mime_content_type') ){
		return mime_content_type($filename);
	}else{
		$mime = include get_include_path().'/Data/Mime.php';
		$mime = (array) $mime;
		if( preg_match("/\.([a-z0-9]{2,4})$/i",$name,$match) ){
			$ext = strtolower($match[1]);
			if( isset($mime[$ext]) ){
				return $mime[$ext][0];
			}
		}
		return "application/octet-stream";
	}
}



/*
	Upload a image-file
     * 	0: Invalid filetype
     * 	1: Exceed size
     *  -1: Unable to upload file
	 *  -2 : Path is not config
     * 	2: Not a file
	 * 	  $config is a array contains properties:
		{
			path =>
			file => in $_FILES,
			old_file  => 
			is_unique => true|false,
			max_size  => value in KB,
			
		}	
*/

function uploadImage( $config=array() ){
	$config['file_type'] = array('gif','jpg','png');
	return upload( $config );
}

function upload( $config=array() ) {
	if( !isset($config['path']) || !is_dir( $config['path'] ) )
		return "Thư mục chứa file không đúng.";
	//relative or absolute path to save file
	$path = $config['path'];
	
	if( !isset($config['path']) ){
		return "Chưa thiết lập đường dẫn thư mục lưu file.";
	} 
	
	//file in $_FILES
	$file = $config['file'];
	
	if( !$file || !isset( $file['tmp_name'] ))
		return "File upload không hợp lệ.";
	
	//die(var_dump($file));
	
	//$config['cmod'] ='777';	
	$file_types = (array)$config['file_type'];

	if(is_file( $file['tmp_name'] )) {
			$filetype = $file['type'];
			$filesize = $file['size'];
			$filename = preg_replace("/[^a-zA-Z\-.]/ui","",create_alias($file['name']));
			
			//Check max size
			if( isset( $config["max_size"] ) OR !is_numeric( $config["max_size"] ) )
				$config["max_size"] = 0;
			if(	$new_file['size'] > get_max_size_upload( $config["max_size"] ) )
				return "File upload có dung lượng quá lớn.";

			//octet-stream is ambigous
			if( $filetype == 'application/octet-stream' ){
				$filetype = get_file_type($file['tmp_name'],$file['name']);
			}
				
			//check file type
			if( count( $file_types ) > 0 ){
				$exts = array();
				$mime = include get_include_path().'/Data/Mime.php';
				$mime = (array) $mime;
				
				foreach( $config['file_type'] as $k){
					if( isset( $mime[$k] ) ){
						$exts = array_merge( $exts, $mime[$k] );
					}	
				}
				if( !in_array($filetype,$exts) ){
					return "Chỉ chấp nhận file có định dạng .".implode(',.',$config['file_type']);;
				}
			}	
				
			//combine from data config
			if( isset( $config["default_value"] )){
				$config["old_file"] = $config["default_value"];
			}	
			//whether or not old_file
			if( !isset( $config["old_file"] ) || ($config["old_file"] ==="" )){
				if( !isset( $config["is_unique_name_upload"] ) OR $config["is_unique_name_upload"] === true ){
					if( file_exists("$path/$filename") ){
						$info  = pathinfo($filename);
						$ext   = $info['extension'];
						$fname = $info['filename'];
						$i = 1;
						while( file_exists( $path."/".$fname."($i).".$ext ) ) $i++;
						$name = $fname."($i).".$ext;
					}else{
						$name = $filename;
					}
				}else{
					$name = $filename;
				}	
			}else{
				if( $config["delete_old_file"] === true ){
					@unlink($path.'/'.$config['old_file']);
				}
				$name = $config["old_file"];
			}
			
			$uploaded_file_full_path = "$path/$name";
			
			if( @move_uploaded_file( $file['tmp_name'], $uploaded_file_full_path ) ) {
				if(isset($config['resize'])&& @filesize($uploaded_file_full_path) ){
					loadClass('PHPThumb');
					$thumb = PhpThumbFactory::create($uploaded_file_full_path);
					$thumb->resize($config['resize'][0],$config['resize'][1]);
					$thumb->save($uploaded_file_full_path,'png');							
					return array($name, 'image/png', filesize($uploaded_file_full_path),$filename);
				}			
				return array($name, $filetype, $filesize,$filename);
			}
			else {
				return "Không thể upload file lên.";
			}
	} else {
		//not file
		return "File upload không hợp lệ.";
	}
}

?>